<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\AdUserAddRequest;
use App\Model\AdminUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Toastr;

class AdUserController extends Controller
{
    protected $fields = [
        'username' => '',
        'password' => '',
    ];

    public function index(Request $request)
    {
        $name = trim($request->name,'');
        $search = array(
            'name' => $name,
        );
        $sql = AdminUser::query();
        $name && $sql->where('username','like','%'.$name.'%');
        $data = $sql->orderBy('id','desc')->paginate(20);
        return view('admin.aduser.index',['data'=>$data,'search'=>$search]);

    }

    public function add()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }

        return view('admin.aduser.add',['data'=>$data]);
    }


    public function add_post(AdUserAddRequest $request){
        $info = new AdminUser();
        foreach (array_keys($this->fields) as $field) {
            $info->$field = !empty($request->input($field)) ?$request->input($field) : '';
        }
        $info->password = md5($info->password);
        $info->remember_token = '';
        $info->save();
        return redirect('/admin/aduser/index')->withSuccess('添加成功！');
    }

    public function edit($id)
    {
        $info = AdminUser::find($id);
        if(!$info){
            return redirect('/admin/aduser/index')->withErrors('找不到该用户!');
        }
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $info->$field);
        }
        $data['id'] = (int)$id;
        return view('admin.aduser.edit', ['data'=>$data]);
    }

    public function edit_post(AdUserAddRequest $request)
    {
        $id = $request->input('id');
        $info = AdminUser::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
            $info->$field = !empty($request->input($field)) ?$request->input($field) : '';
        }
        $info->password = md5($info->password);
        $info->save();
        return redirect('/admin/aduser/index')->withSuccess('编辑成功！');
    }

    public function delete($id)
    {
        $tag = AdminUser::find((int)$id);
        if ($tag) {
            if($tag->username == 'admin'){
                Toastr::error('该账户不能删除');
                return redirect()->back();
            }
            $tag->delete();
        } else {
            Toastr::error('删除失败');
            return redirect()->back();
        }
        Toastr::success('删除成功');
        return redirect()->back();
    }


}
